#include "HybridWidget.h"
#include <QDebug>

unsigned int HybridWidget::frameTime = 10;
//--------------------------------------------------------------------------
HybridWidget::HybridWidget(QWidget* Parent):QWidget(Parent),initialized (false)
{
    world = new World(this);

    // Setup some states to allow direct rendering into the widget
    setAttribute(Qt::WA_PaintOnScreen);
    setAttribute(Qt::WA_OpaquePaintEvent);
    setAttribute(Qt::WA_NoSystemBackground);

    // Set strong focus to enable keyboard events to be received
    setFocusPolicy(Qt::StrongFocus);

    // Setup the widget geometry
    QPoint p(0, 0);
    QSize s(Parent->width(), Parent->height());
    move(p);
    resize(s);

    // Setup the timer
    timer.setInterval(frameTime);
}
//--------------------------------------------------------------------------
#ifdef Q_WS_X11
    #include <Qt/qx11info_x11.h>
    #include <X11/Xlib.h>
#endif
void HybridWidget::showEvent(QShowEvent*)
{
    if (!initialized)
    {
        // Under X11, we need to flush the commands sent to the server to ensure that
        // SFML will get an updated view of the windows
        #ifdef Q_WS_X11
            XFlush(QX11Info::display());
        #endif

        // Create the SFML window with the widget handle
        RenderWindow::create(reinterpret_cast<sf::WindowHandle>(winId()));

        // Setup the timer to trigger a refresh at specified framerate
        connect(&timer, SIGNAL(timeout()), this, SLOT(repaint()));
        timer.start();

        initialized = true;
    }
}
//--------------------------------------------------------------------------
QPaintEngine* HybridWidget::paintEngine() const
{
    return 0;
}
//--------------------------------------------------------------------------
void HybridWidget::paintEvent(QPaintEvent*)
{
    world->scenario(frameTime);
    if (!world->isWindowOpen()) emit closed();
}
